package com.zx.ticket.controller.admin;

import com.zx.ticket.entity.Admin;
import com.zx.ticket.service.AdminService;
import com.zx.ticket.util.DESUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping(value = "/admin")
public class adminController {

    @Autowired
    private AdminService adminService;

    @GetMapping(value = "/login")
    public String login()
    {
        return "admin/login";
    }

    @GetMapping("/register")
    public String signup()
    {
        return "/admin/register";
    }

    @PostMapping("/register")
    public String register(HttpServletRequest request)
    {
        Admin admin = new Admin();
        String username = request.getParameter("username");
        String password1 = request.getParameter("password");
        String password = DESUtils.getEncryptString(password1);
        System.out.println(password);
        System.out.println(password1);
        admin.setUsername(username);
        admin.setPassword(password);
        adminService.addAdmin(admin);
        return "/admin/login";

    }

    @PostMapping(value = "/logins")
    public String logins(@ModelAttribute Admin admin,Model model, HttpServletRequest request, HttpSession session) throws IOException {
        String username = request.getParameter("username");
        String password1 = request.getParameter("password");
        String password = DESUtils.getEncryptString(password1);
        admin.setUsername(username);
        admin.setPassword(password);
        admin = this.adminService.selectByUsernameAndPassword(admin);
        if (admin != null)
        {
            session.setAttribute("admin",admin);
            return "/admin/index";
        }
        else
        {
            model.addAttribute("errormsg","账号或密码错误");
            //session.setAttribute("errormsg","账号或密码错误");
            return "/test";
        }
    }

    @GetMapping("/index")
    public String index()
    {
        return "admin/index";
    }

}
